//
//  WalletVc.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2019/1/3.
//  Copyright © 2019 Gox_WallyDiao. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyStoreKit


class WalletVc: TTBaseVC {
    
    fileprivate let MineCellID = "MineCell"
    
    let arr = ["交易记录", "听币明细记录"]
    var sesionHeight:CGFloat = 210.0
    lazy var topView:WalletTopView = {
        let top = WalletTopView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, 147))
        return top
    }()
    
    lazy var headerView:UIView = {
        let header = UIView.init()
        header.backgroundColor = WhiteBackColor
        return header
    }()
    
    lazy var tableView: UITableView = {
        let tableView = UITableView.init(frame: FRAME_CGFloat(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - OFFSET_TOP), style: UITableView.Style.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        //        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.bounces = true
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.register(NIBNAME(MineCellID), forCellReuseIdentifier: MineCellID)
        
        tableView.tableFooterView = UIView.init(frame: .zero)
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "我的钱包"
        self.view.addSubview(self.tableView)
        SET_LINEVIEW(view: self.view)
        self.tableView.tableHeaderView = headerView
        self.headerView.addSubview(topView)
        
        setData()
        
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setTopData()
    }
    
    func setData() {

        MineRequestModel.loadExchangeRate { (success, message, model) in
            if success && model != nil {
                let height = self.countToHeight(count: model?.count ?? 1)
                let centre = WalletCentreView.init(frame: FRAME_CGFloat(0, 147, SCREEN_WIDTH, height + 110), height: height)
                centre.modelList = model
                centre.delegate = self
                self.sesionHeight = height + 110
                self.headerView.addSubview(centre)
                self.headerView.frame = FRAME_CGFloat(0, 0, SCREEN_WIDTH, height + 110 + 147)
                self.tableView.reloadData()
            }
        }
        
    }
    
    func setTopData() {
        MineRequestModel.loadWalletBalance(jointArr: [String.getUserId()]) { (success, message, left, right) in
            if success {
                self.topView.leftLabel.text = "\(String.money(left) ?? "0.00")"
                self.topView.rightlabel.text = "\(String.money(right) ?? "0.00")"
            }
        }
    }
    
    func countToHeight(count:Int) -> CGFloat {
        let height = (count / 3 + 1) * 71
        return CGFloat(height)
    }
    
    func purchase(_ productId:String, _ price:String) {
        MTProgressHUD.show()
    
        SwiftyStoreKit.purchaseProduct(productId, quantity: 1, atomically: true, applicationUsername: "", simulatesAskToBuyInSandbox: false) { (result) in
            MTProgressHUD.hidded(true)
            switch result {
            case .success(let product):
                self.fetch(product.productId, price)
            case .error(let error):
                switch error.code {
                case .unknown: print("Unknown error. Please contact support")
                case .clientInvalid: print("Not allowed to make the payment")
                case .paymentCancelled: break
                case .paymentInvalid: print("The purchase identifier was invalid")
                case .paymentNotAllowed: print("The device is not allowed to make the payment")
                case .storeProductNotAvailable: print("The product is not available in the current storefront")
                case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
                case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
                case .cloudServiceRevoked: print("User has revoked permission to use this cloud service")
                default: print((error as NSError).localizedDescription)
                }
            }
        }
    }
    
    func fetch(_ productId:String, _ price:String) {
        SwiftyStoreKit.fetchReceipt(forceRefresh: false) { result in
            switch result {
            case .success(let receiptData):
                let encryptedReceipt = receiptData.base64EncodedString(options: [])
                let para = ["body": "天天必听",
                            "price": price,
                            "inReceipt": encryptedReceipt,
                            "userId": String.getUserId()] as [String : Any]
                MineRequestModel.CheckPay(parameters: para, completion: { (suc, mes) in
                    if suc {
                        self.setTopData()
                    } else {
                        TTAlertView.showMessage(message: mes, second: 2)
//                        self.verify(productId, price)
                    }
                })
            case .error(let error):
                print("Fetch receipt failed: \(error)")
            }
        }
    }
    
    /*
    func verify(_ productId:String, _ price:String) {
        let receippt = AppleReceiptValidator(service: .sandbox, sharedSecret: SharedSecret)
        SwiftyStoreKit.verifyReceipt(using: receippt, completion: { (result) in
            print(result)
            switch result {
            case .success(let receipt):
  
                let productId = productId
                // Verify the purchase of Consumable or NonConsumable
                let purchaseResult = SwiftyStoreKit.verifyPurchase(
                    productId: productId,
                    inReceipt: receipt)
                
                switch purchaseResult {
                case .purchased(let receiptItem):
                    print("\(productId) is purchased: \(receiptItem)")
                    
                case .notPurchased:
                    print("The user has never purchased \(productId)")
                }
            case .error(let error):
                print("Receipt verification failed: \(error)")
            }
        })
    }
 */
    
}

//  MARK: - ###### 协议 ######
extension WalletVc:UITableViewDelegate, UITableViewDataSource, WalletCentreViewDelegate {
    func payActionDele(productId:String, price:String) {
        self.purchase(productId,price)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: MineCellID) as! MineCell
        cell.titleLabel.text = arr[indexPath.row]
        cell.titleLabel.textColor = RGB_Same(136)
        cell.selectionStyle = .none
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 0:
            let playVc = TradingRecordVc()
            PUSHVIEWCONTROLLER(playVc)
        case 1:
            let playVc = TBWithdrawVc()
            PUSHVIEWCONTROLLER(playVc) 
        default:
            return
        }
        
        
    }
    
}

//  MARK: - ###### 事件处理 ######
extension WalletVc {
    
}

//  MARK: - ###### 私有方法 ######
extension WalletVc {
    
    
}

//  MARK: - ###### 公有方法 ######
extension WalletVc {
    
}
